昨天把開發環境的MongoDB透過Docker架起來了
今天要把前面Go的Http與MongoDB進行整合並串接
製作成一個完整的API![]()
我希望這次有的是店家的新增功能
資料格式有如下
    StoreName: string
    Addr: string
    Alias: string
    Phone: string
    WebSite: string
    Image: string
資料格式定義好了以後就是要來弄路由
在前天有製作了Router的檔案其中init是定義路由
今天新增一個POST的路由
register("POST", "/api/store", controller.CreateStore, nil)
並且新增一個資料夾叫controller(負責控制商業邏輯)
新增一個storeController.go
並開一個CreateStore的方法
package controller
import (
	"OrderApi/model"
	"OrderApi/services"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)
func CreateStore(w http.ResponseWriter, r *http.Request) {
	setupResponse(&w, r)
	b, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	var store model.Store
	err = json.Unmarshal(b, &store)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	services.SaveStore(store)
}
新增一個資料夾services並在其中新增一個mongoService.go
package services
import (
	"OrderApi/model"
	"context"
	"fmt"
	"time"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)
func SaveStore(store interface{}) {
	fmt.Println("Save Store")
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	defer func() {
		if err = client.Disconnect(ctx); err != nil {
			panic(err)
		}
	}()
	database := client.Database("OrderAPI")
	storeCol := database.Collection("Store")
	storeCol.InsertOne(ctx, store)
}
這樣就設置完成整個從
Main=>Router=>Controller=>Service=>DB
資料流了

這樣就完成了一整個HttpServer 從Http發Request到落地的整個流程